package com.heima.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.user.IUserClient;
import com.heima.comment.service.AppCommentService;
import com.heima.common.constants.CommentComstants;
import com.heima.common.redis.CacheService;
import com.heima.model.comment.dtos.CommentDto;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.model.comment.dtos.CommentSaveDto;
import com.heima.model.comment.pojos.ApUserComment;
import com.heima.model.comment.vos.CommentLoadVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class AppCommentServiceImpl implements AppCommentService {

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private IUserClient userClient;
    /**
     * 发布评论
     * @param dto
     * @return
     */
    @Override
    public ResponseResult save(CommentSaveDto dto) {
        //检验入参，且评论不可为空
        if(dto==null || StringUtils.isBlank(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtil.getUser();

        ApUserComment apUserComment = new ApUserComment();
        apUserComment.setUserId(user.getId());
        apUserComment.setArticleId(dto.getArticleId());
        apUserComment.setContent(dto.getContent());
        apUserComment.setLikes(0);
        apUserComment.setReply(0);
        apUserComment.setCreatedTime(new Date());

        mongoTemplate.save(apUserComment);
        //通过kafka stream 更改article的评论数
        kafkaTemplate.send(CommentComstants.ARTICLE_COMMENT_TOPIC,dto.getArticleId().toString());
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 查询评论列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(CommentDto dto) {
        //检验入参
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //查询评论详情
        List<ApUserComment> commentList = mongoTemplate.find(Query.query(Criteria.where("articleId").is(dto.getArticleId())
                .and("createdTime").lt(dto.getMinDate())
        ).limit(10).with(Sort.by(Sort.Order.desc("createdTime"))), ApUserComment.class);

        //创建一个集合存放返回对象
        ArrayList<CommentLoadVo> voList = new ArrayList<>();

        //获取当前用户Id，用于查询是否对评论点赞
        ApUser apUser = AppThreadLocalUtil.getUser();

        //查询redis，查看是否点赞
        String likeString = cacheService.get(CommentComstants.COMMENT_LIKE + apUser.getId());
        List<ObjectId> commentIdList = JSON.parseArray(likeString, ObjectId.class);

        //封装数据
        for (ApUserComment comment : commentList) {
            CommentLoadVo vo = new CommentLoadVo();
            BeanUtils.copyProperties(comment,vo);
            vo.setId(comment.getId().toString());
            vo.setAuthorId(comment.getUserId());
            vo.setEntryId(comment.getArticleId());
            vo.setType(0);
            ResponseResult result = userClient.findUser(comment.getUserId());
            ApUser user = JSON.parseObject(JSON.toJSONString(result.getData()), ApUser.class);
            vo.setAuthorName(user.getName());
            //判断是否点赞
            if(commentIdList!=null && commentIdList.contains(comment.getId())){
                vo.setOperation(0);
            }
            voList.add(vo);
        }

        return ResponseResult.okResult(voList);
    }

    /**
     * 点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDto dto) {
        //往redis添加用户点赞记录或取消点赞
        if(dto==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取用户id
        ApUser user = AppThreadLocalUtil.getUser();
        if(dto.getOperation()==0){
            //点赞
            cacheService.lLeftPush(CommentComstants.COMMENT_LIKE + user.getId(),dto.getCommentId().toString());
            //修改文章端的点赞数
            ApUserComment comment = mongoTemplate.findById(dto.getCommentId(), ApUserComment.class);
            if(comment.getLikes()==null){
                comment.setLikes(1);
            }else {
                comment.setLikes(comment.getLikes()+1);
            }
            //保存
            mongoTemplate.save(comment);
        }else {
            //取消点赞
            cacheService.lRemove(CommentComstants.COMMENT_LIKE + user.getId(),0,dto.getCommentId().toString());
            //修改文章端的点赞数
            ApUserComment comment = mongoTemplate.findById(dto.getCommentId(), ApUserComment.class);
            if(comment.getLikes()==null){
                comment.setLikes(1);
            }else {
                comment.setLikes(comment.getLikes()-1);
            }
            //保存
            mongoTemplate.save(comment);

        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
